package cn.xiaosiyuan.util.network.http;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;

public class HttpHandler {

    public static HttpURLConnection getConn(String url,
                                            Map<String,String> headers) throws IOException {
        //创建远程url连接对象
        URL httpUrl = new URL(url);
        //通过远程url连接对象打开一个连接，强转成httpURLConnection类
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        //设置连接主机服务器的超时时间:15000毫秒
        connection.setConnectTimeout(15 * 1000);
        //设置读取远程返回的数据时间:60000毫秒
        connection.setReadTimeout(60 * 1000);
        //设置请求头
        if (headers != null) {
            Iterator<String> iterator = headers.keySet().iterator();
            while (iterator.hasNext()) {
                String next =  iterator.next();
                connection.addRequestProperty(next, headers.get(next));
            }
        }
        return connection;
    }


    public static String handleResult(HttpURLConnection connection) throws IOException {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            int code = connection.getResponseCode();
            if (code == 200) {
                is = connection.getInputStream();
                isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                br = new BufferedReader(isr);
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                return sbf.toString();
            } else {
                throw new RuntimeException("error,responescode=" + code);
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (br != null) {
                br.close();
            }
        }
    }

    public static String doGet(String url,Map<String,String> headers) {
        HttpURLConnection connection = null;
        try {
            getConn(url, headers);
            connection.setRequestMethod("GET");
            connection.connect();
            String handleResult = handleResult(connection);
            return handleResult;
        } catch (IOException e) {
            throw new Error(e);
        } finally {
            connection.disconnect();
        }
    }

    public static String doPost(String url,Map<String,String> headers,String params) throws IOException {
        HttpURLConnection connection = null;
        OutputStream os = null;
        try {
            connection = getConn(url, headers);
            // 设置请求方式为GET
            connection.setRequestMethod("POST");
            //默认值为:false,当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为:true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            //通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(params.getBytes());
            //通过connection连接，获取输入流
            String handleResult = handleResult(connection);
            return handleResult;
        } catch (IOException e) {
            throw new Error(e);
        } finally {
            os.close();
            connection.disconnect();
        }
    }

}